package com.arqui.admmon_module.server.handlers;

import java.net.UnknownHostException;
import co.edu.unal.satacredito.database.connection.AdministratorDatastoreFactory;
import co.edu.unal.satacredito.database.dao.BrandMongoDao;
import co.edu.unal.satacredito.database.entity.Brand;
import co.edu.unal.satacredito.database.entity.exceptions.PreexistingEntityException;
import com.gwtplatform.dispatch.server.actionhandler.ActionHandler;
import com.arqui.admmon_module.client.action.SaveBrand;
import com.arqui.admmon_module.client.action.SaveBrandResult;
import com.google.code.morphia.Datastore;
import com.google.inject.Inject;
import com.gwtplatform.dispatch.server.ExecutionContext;
import com.gwtplatform.dispatch.shared.ActionException;
import com.mongodb.MongoException;

public class SaveBrandActionHandler implements
		ActionHandler<SaveBrand, SaveBrandResult> {

	private Datastore ds;
    private BrandMongoDao instance;
    private Brand brand;
	private SaveBrandResult result;
	
	@Inject
	public SaveBrandActionHandler() {
	}

	@Override
	public SaveBrandResult execute(SaveBrand action, ExecutionContext context) throws ActionException {
		Boolean r = false;
		String message = "No se guardo el establecimiento.";
		String message_exi = "El establecimiento ya existe.";
		String message_null = "Hay datos nulos.";
		String message_data = "Verifique que la conexión este activada.";
		
		result = new SaveBrandResult(r,message);
		
		
		
		if(action.getCel().equals(null) || action.getEmail().isEmpty() || action.getLastnamerepre().isEmpty() || action.getName().isEmpty() || action.getNamerepre().isEmpty() || 
				action.getNit().equals(null) || action.getRepreid().equals(null) || action.getServiceName().isEmpty()){
			result.setMessage(message_null);
			return result;
		}
		
		try {
			ds = AdministratorDatastoreFactory.createDatastore();
			instance = new BrandMongoDao(ds);
			
		}	catch (UnknownHostException | MongoException e) {
			result.setMessage(message_data);
			return result;
		}	
		
		try {
			instance.create(brand);
		} catch (PreexistingEntityException e) {
			result.setMessage(message_exi);
			return result;
		}
		result.setMessage("");
		result.setState(true);
		return result;
		
	}

	@Override
	public void undo(SaveBrand action, SaveBrandResult result,
			ExecutionContext context) throws ActionException {
	}

	@Override
	public Class<SaveBrand> getActionType() {
		return SaveBrand.class;
	}
}
